package com.example.woke;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.tencent.bugly.beta.Beta;
import com.woke.data.UserPromoteCode;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.OnekeyShareTheme;

public class SettingActivity extends Activity {

	private String version;//�汾��
	private AlertDialog alertDialog;
	private String versioname;
	private MyApp app;
	private boolean isDestroy = true;
	private boolean isBinded;
	private TextView mTtime;
	private ClipData myClip;
	private ClipboardManager myClipboard;
	//	public static String TEST_IMAGE;
//	private static final String FILE_NAME = "/ic_icon2.jpg";
//	private String shareurl;
	private String shareurl = "这个软件非常棒！邀请您下载中财在线APP体验下，网址:www.88china.com,客服:400-6080608";
	private int mOrgId;
	private ArrayList<UserPromoteCode> mPromoteCodeList;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_setting);

		version = getVersion ();
		app = (MyApp) getApplication ();
		intview ();

	}



	public String getVersion() {
		try {
			android.content.pm.PackageManager manager = SettingActivity.this.getPackageManager ();
			android.content.pm.PackageInfo info = manager.getPackageInfo (SettingActivity.this.getPackageName (), 0);
			versioname = info.versionName;
			int versionCode = info.versionCode;
			return "" + versionCode;
		} catch (Exception e) {
			e.printStackTrace ();
			return "";
		}
	}

	private void getpersondata() {
		AsyncHttpClient ahc = new AsyncHttpClient ();
		PersistentCookieStore myCookieStore = new PersistentCookieStore (SettingActivity.this);
		ahc.setCookieStore (myCookieStore);
		RequestParams params = new RequestParams ();
		params.put ("g", "api");
		params.put ("m", "Ads");
		params.put ("a", "adsList");
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				Log.e ("r上", "" + response);
				try {
					String flag = response.getString ("flag");
					if (flag.equals ("success")) {
						JSONObject jsonObject = response.getJSONObject ("data");
						JSONArray arra = jsonObject.getJSONArray ("data");
						for (int i = 0; i < arra.length (); i++) {
							JSONObject data = arra.getJSONObject (i);
							String ad_content = data.getString ("ad_content");
							String ad_pic = data.getString ("ad_pic");
							String ad_url = data.getString ("ad_url");
							String status = data.getString ("status");
							String ad_name = data.getString ("ad_name");
							String ad_id = data.getString ("ad_id");
							if (i == 0) {
								String strBase64 = new String (Base64.encode ("1".getBytes (), Base64.DEFAULT));
								shareurl = ad_url + "/NOxBL7xp/" + strBase64;
							}
						}
					}
				} catch (JSONException e) {
					e.printStackTrace ();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure (statusCode, headers, responseString, throwable);
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart ();
			}

			@Override
			public void onFinish() {
				super.onFinish ();
//				mBar.setVisibility(View.GONE);
				Log.e ("response", "完成");
			}
		});
	}

	private void intview() {
//		// ��ʼ��ͼƬ·��
//				new Thread() {
//				public void run() {
//				initImagePath();
//				}
//				}.start();
		myClipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
		mTtime = (TextView) findViewById (R.id.avsetting_text_lasttiem);
		if (app.getDatas_load () != null) {
			mTtime.setText (app.getDatas_load ().getLast_login_time ());
		}
		findViewById (R.id.avsetting_relative_about).setOnClickListener (new OnClickListener () {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent (SettingActivity.this, AboutActivity.class);
				startActivity (intent);
			}
		});

		findViewById (R.id.avsetting_relative_psw).setOnClickListener (new OnClickListener () {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent (SettingActivity.this, PswchangeActivity.class);
				intent.putExtra ("name", 1);
				startActivity (intent);
			}
		});


		findViewById (R.id.avsetting_image_back).setOnClickListener (new OnClickListener () {

			@Override
			public void onClick(View v) {
				finish ();
			}
		});

		findViewById (R.id.avsetting_relative_app).setOnClickListener (new OnClickListener () {
			@Override
			public void onClick(View v) {
				Beta.checkUpgrade ();
//				getpayid ();
			}
		});

		findViewById (R.id.avsetting_relative_add).setOnClickListener (new OnClickListener () {
			@Override
			public void onClick(View v) {
				showShare ();
			}
		});

		findViewById (R.id.avsetting_relative_history).setOnClickListener (new OnClickListener () {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent (SettingActivity.this, HistoryActivity.class);
				startActivity (intent);
			}
		});
		getpRromoteFromHttp();
//		getpersondata ();
	}

	private void showShare() {
//		ShareSDK.initSDK (this);
		OnekeyShare oks = new OnekeyShare ();
//		Platform weibo = ShareSDK.getPlatform(Wechat.w);
		// �ο����������½ڣ����÷������
		// ����һ��ͼ��
		Bitmap enableLogo = BitmapFactory.decodeResource (getResources (), R.drawable.ssdk_oks_logo_fuzhi);
		String label = "复制链接";
		OnClickListener listener = new OnClickListener () {
			public void onClick(View v) {
				myClip = ClipData.newPlainText ("text", getResources().getString(R.string.oem_friend_tuijian));
				myClipboard.setPrimaryClip (myClip);
				Toast.makeText (getApplicationContext (), "已复制到剪贴板",
						Toast.LENGTH_SHORT).show ();
			}
		};
		oks.setTheme (OnekeyShareTheme.CLASSIC);

		oks.disableSSOWhenAuthorize ();
		oks.setCustomerLogo (enableLogo, label, listener);
		oks.setTitle (getResources().getString(R.string.oem_title_tuijian_share));
		oks.setTitleUrl (shareurl);
		oks.setText (getResources().getString(R.string.oem_content_tuijian_share));

		oks.setImageUrl (getResources().getString(R.string.oem_url_tuijian_share));
		oks.setUrl (shareurl);
		oks.setComment (getResources ().getString (R.string.app_name));
		oks.setSite (getResources().getString(R.string.oem_title_tuijian_share));
		oks.setSiteUrl (shareurl);
		oks.setVenueName (getResources ().getString (R.string.app_name));
		// ��������GUI
		oks.setCallback(new PlatformActionListener() {
			@Override
			public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
				Log.d("ShareLogin", "onComplete ---->  分享成功");
				platform.getName();
			}

			@Override
			public void onError(Platform platform, int i, Throwable throwable) {
				Log.d("ShareLogin", "onError ---->  失败" + throwable.getStackTrace().toString());
				Log.d("ShareLogin", "onError ---->  失败" + throwable.getMessage());
			}
			@Override
			public void onCancel(Platform platform, int i) {
				Log.d("ShareLogin", "onCancel ---->  分享取消");
			}
		});
		oks.show (this);
	}
	public void getpRromoteFromHttp() {
		Log.e ("UserPromoteActivity", "getpRromoteFromHttp");
		AsyncHttpClient ahc = new AsyncHttpClient ();
		PersistentCookieStore myCookieStore = new PersistentCookieStore (SettingActivity.this);
		ahc.setCookieStore (myCookieStore);
		RequestParams params = new RequestParams ();
		params.put ("g", "Api");
		params.put ("m", "user");
		params.put ("a", "myPromocode");
		params.put ("type","1");
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart ();
				Log.e ("PromoteCodeFragment", "OnStart");
			}

			@Override
			public void onSuccess(int statusCode, Header[] headers,
								  JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				if (response != null) {
					Log.e ("PromoteCode", response.toString ());

				}
				if (response != null) {
					try {
						String flag = response.getString ("flag");
						if (flag.equals ("success")) {
							JSONObject json = response.getJSONObject ("data");
							JSONArray array = json.getJSONArray ("data");
							Gson gson = new Gson ();
							Type type = new TypeToken<ArrayList<UserPromoteCode>>() {
							}.getType ();
							mPromoteCodeList = gson.fromJson (array.toString (),
									type);
							if (mPromoteCodeList != null && mPromoteCodeList.size () > 0) {
								mOrgId=mPromoteCodeList.get(0).getId();
								getmyerweima();
							}
						} else {
							String info = response.getString ("info");
							Toast.makeText (SettingActivity.this, info,
									Toast.LENGTH_SHORT).show ();
						}

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace ();
					}
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
								  String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				super.onFailure (statusCode, headers, responseString, throwable);
				Log.e ("UserPromote", "onFailure");
			}

			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				super.onFinish ();
			}
		});

	}
	private void getmyerweima() {
		if (mOrgId == -1) return;
		AsyncHttpClient ahc = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "user");
		//		params.put("a", typeString);
		params.put("a", "promocodeDetail");

		params.put("userid", app.getDatas_load().getId());
		params.put("orgid", mOrgId);

		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
								  JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				Log.e("onSuccess" + app.getDatas_load().getId(), "--" + response);
				try {
					String flag = response.getString("flag");
					if (flag.equals("success")) {
						JSONObject jsonObject = response.getJSONObject("data");
						JSONObject jsonObject2 = jsonObject
								.getJSONObject("data");
						//						String string = jsonObject2.getString("code");
						// {"flag":"success","info":"操作成功","data":{"data":{"code":"app.88china.com:8384\/data\/upload\/qrcode\/be11f3301dbaba5d.png","url":"http:\/\/app.88china.com:8384\/index.php?g=api&m=Register&a=index&type=1&invitation_code=18759266591"}},"time":1483526253}
						//						Log.e("UserPromote", string);
						String string = jsonObject2.getString("url");
						shareurl = jsonObject2.getString("url");
						System.out.println(string);

					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
								  String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
			}

			@Override
			public void onStart() {
				super.onStart();
			}

			@Override
			public void onFinish() {
				super.onFinish();
			}
		});
	}
}
